from ppocronnx.predict_system import TextSystem
import numpy as np
import cv2 as cv
from utils.log import log

class OCRUtils:
    def __init__(self, lang='ch'):
        self.lang = lang
        self.ts = TextSystem(use_angle_cls=False)
        self.ts.text_recognizer.postprocess_op.character.append(' ')
        self.text = ''
    
    def input(self, img):
        try:
            self.text=self.ts.ocr_single_line(img)[0].lower()
        except:
            self.text=''

    # 查找相似文本
    def sim(self, text, img=None):
        if img is not None:
            self.input(img)
        self.text = self.text.strip()
        if self.nothing == False:
            if text.lower() == self.text.lower() or text.lower() in self.text.lower():
                return True
        return False
    
    def find_text(self, img, text, env=None):
        self.nothing = True
        results = self.ts.detect_and_ocr(img)
        lists = []
        for txt in text:
            for res in results:
                self.text = res.ocr_text
                if len(self.text.strip()) > 0 and 'UID' not in self.text:
                    self.nothing = False
                if self.sim(txt):
                    print("识别到文本：", txt, "匹配文本：", self.text, "相似度：", res.score)
                    lists.append(res)
        if len(lists) > 0:
            return max(lists, key=lambda p: p.score).box
        else:
            return None